<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>腾讯云COS上传测试</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            line-height: 1.6;
            color: #333;
            background-color: #f5f5f5;
        }
        
        .container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .header {
            text-align: center;
            margin-bottom: 30px;
            padding: 20px 0;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        
        .header h1 {
            color: #1890ff;
            font-size: 24px;
        }
        
        .card {
            background: #fff;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        
        .card h2 {
            font-size: 18px;
            margin-bottom: 15px;
            color: #1890ff;
            padding-bottom: 10px;
            border-bottom: 1px solid #f0f0f0;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: 500;
            color: #666;
        }
        
        .form-group input[type="file"] {
            padding: 10px;
            border: 1px solid #d9d9d9;
            border-radius: 4px;
            width: 100%;
            font-size: 14px;
        }
        
        .options {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-bottom: 15px;
        }
        
        .option-item {
            display: flex;
            align-items: center;
        }
        
        .option-item input[type="checkbox"] {
            margin-right: 5px;
        }
        
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s;
            margin-right: 10px;
        }
        
        .btn-primary {
            background: #1890ff;
            color: #fff;
        }
        
        .btn-primary:hover {
            background: #40a9ff;
        }
        
        .btn-success {
            background: #52c41a;
            color: #fff;
        }
        
        .btn-success:hover {
            background: #73d13d;
        }
        
        .btn-warning {
            background: #faad14;
            color: #fff;
        }
        
        .btn-warning:hover {
            background: #ffc53d;
        }
        
        .btn-danger {
            background: #f5222d;
            color: #fff;
        }
        
        .btn-danger:hover {
            background: #ff4d4f;
        }
        
        .progress {
            width: 100%;
            height: 20px;
            background: #f5f5f5;
            border-radius: 10px;
            overflow: hidden;
            margin-bottom: 10px;
            position: relative;
        }
        
        .progress-bar {
            height: 100%;
            background: #1890ff;
            transition: width 0.3s;
        }
        
        .progress-text {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            color: #333;
        }
        
        .hidden {
            display: none;
        }
        
        .result {
            margin-top: 20px;
            padding: 15px;
            background: #f0f5ff;
            border: 1px solid #adc6ff;
            border-radius: 4px;
        }
        
        .result h3 {
            font-size: 16px;
            margin-bottom: 10px;
            color: #1890ff;
        }
        
        .result pre {
            background: #fafafa;
            padding: 10px;
            border-radius: 4px;
            overflow-x: auto;
            font-family: 'Courier New', Courier, monospace;
            font-size: 14px;
            white-space: pre-wrap;
            word-wrap: break-word;
        }
        
        .uploaded-files {
            margin-top: 20px;
        }
        
        .file-item {
            padding: 10px;
            background: #fafafa;
            border-radius: 4px;
            margin-bottom: 10px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .file-info {
            flex: 1;
        }
        
        .file-name {
            font-weight: 500;
            color: #333;
        }
        
        .file-size {
            font-size: 12px;
            color: #999;
        }
        
        .file-actions button {
            padding: 5px 10px;
            border: none;
            border-radius: 4px;
            font-size: 12px;
            cursor: pointer;
            margin-left: 5px;
        }
        
        .success-message {
            color: #52c41a;
        }
        
        .error-message {
            color: #f5222d;
        }
        
        .loading {
            display: inline-block;
            width: 16px;
            height: 16px;
            border: 2px solid #f3f3f3;
            border-top: 2px solid #1890ff;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-right: 5px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .image-preview {
            margin-top: 10px;
            max-width: 100%;
            max-height: 300px;
            border-radius: 4px;
            border: 1px solid #d9d9d9;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>腾讯云COS上传测试</h1>
        </div>
        
        <div class="card">
            <h2>上传配置</h2>
            <div class="form-group">
                <label for="upload-file">选择文件：</label>
                <input type="file" id="upload-file" name="file" accept="*/*">
            </div>
            
            <div class="options">
                <div class="option-item">
                    <input type="checkbox" id="save-to-db" checked>
                    <label for="save-to-db">保存到数据库</label>
                </div>
                <div class="option-item">
                    <input type="checkbox" id="show-preview" checked>
                    <label for="show-preview">显示预览（仅图片）</label>
                </div>
            </div>
            
            <div class="progress hidden">
                <div class="progress-bar" style="width: 0%"></div>
                <div class="progress-text">0%</div>
            </div>
            
            <div>
                <button id="btn-simple-upload" class="btn btn-primary">简单上传</button>
                <button id="btn-slice-upload" class="btn btn-success">分片上传</button>
                <button id="btn-auto-upload" class="btn btn-warning">自动选择上传方式</button>
                <button id="btn-clear" class="btn btn-danger">清空</button>
            </div>
        </div>
        
        <div class="card">
            <h2>上传结果</h2>
            <div id="result" class="result hidden">
                <h3>上传信息</h3>
                <pre id="result-content"></pre>
            </div>
            
            <div id="uploaded-files" class="uploaded-files hidden">
                <h3>已上传文件</h3>
                <div id="file-list"></div>
            </div>
        </div>
        
        <div class="card">
            <h2>功能说明</h2>
            <ul>
                <li>简单上传：适用于小文件（建议小于10MB）</li>
                <li>分片上传：适用于大文件（大于10MB）</li>
                <li>自动选择：根据文件大小自动选择上传方式</li>
                <li>上传进度：实时显示上传进度</li>
                <li>结果查看：上传成功后显示文件信息和访问URL</li>
                <li>文件预览：上传图片时可直接查看预览</li>
            </ul>
        </div>
    </div>
    
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(function() {
            // 已上传的文件列表
            let uploadedFiles = [];
            
            // 上传方式映射
            // const uploadUrls = {
            //     simple: 'http://localhost:11011/admin/cos_upload/simpleUpload',
            //     slice: 'http://localhost:11011/admin/cos_upload/sliceUpload',
            //     auto: 'http://localhost:11011/admin/cos_upload/autoUpload'
            // };
            const uploadUrls = {
                simple: '/admin/cos_upload/simpleUpload',
                slice: '/admin/cos_upload/sliceUpload',
                auto: '/admin/cos_upload/autoUpload'
            };
            // 简单上传
            $('#btn-simple-upload').click(function() {
                uploadFile('simple');
            });
            
            // 分片上传
            $('#btn-slice-upload').click(function() {
                uploadFile('slice');
            });
            
            // 自动选择上传
            $('#btn-auto-upload').click(function() {
                uploadFile('auto');
            });
            
            // 清空
            $('#btn-clear').click(function() {
                $('#upload-file').val('');
                $('#result').addClass('hidden');
                $('#progress').addClass('hidden');
                $('#progress-bar').css('width', '0%');
                $('#progress-text').text('0%');
                $('.image-preview').remove();
            });
            
            // 文件上传函数
            function uploadFile(type) {
                const fileInput = $('#upload-file')[0];
                if (!fileInput.files || fileInput.files.length === 0) {
                    alert('请先选择要上传的文件');
                    return;
                }
                
                const file = fileInput.files[0];
                const formData = new FormData();
                formData.append('file', file);
                formData.append('save_db', $('#save-to-db').is(':checked') ? 1 : 0);
                
                // 显示进度条
                $('#progress').removeClass('hidden');
                $('#progress-bar').css('width', '0%');
                $('#progress-text').text('0%');
                
                // 禁用按钮
                $('#btn-simple-upload, #btn-slice-upload, #btn-auto-upload').prop('disabled', true);
                
                // 执行上传
                $.ajax({
                    url: uploadUrls[type],
                    type: 'POST',
                    data: formData,
                    contentType: false,
                    processData: false,
                    xhr: function() {
                        const xhr = $.ajaxSettings.xhr();
                        // 监听上传进度
                        xhr.upload.addEventListener('progress', function(e) {
                            if (e.lengthComputable) {
                                const percentComplete = (e.loaded / e.total) * 100;
                                $('#progress-bar').css('width', percentComplete + '%');
                                $('#progress-text').text(Math.round(percentComplete) + '%');
                            }
                        }, false);
                        return xhr;
                    },
                    success: function(res) {
                        if (res.code === 1) {
                            // 显示结果
                            $('#result-content').text(JSON.stringify(res.data, null, 2));
                            $('#result').removeClass('hidden');
                            
                            // 添加到文件列表
                            addToFileList(file, res.data);
                            
                            // 显示预览（仅图片）
                            if ($('#show-preview').is(':checked') && file.type.startsWith('image/')) {
                                showImagePreview(res.data.url);
                            }
                            
                            alert('上传成功！');
                        } else {
                            alert('上传失败：' + res.msg);
                        }
                    },
                    error: function(xhr, status, error) {
                        alert('上传出错：' + error);
                    },
                    complete: function() {
                        // 启用按钮
                        $('#btn-simple-upload, #btn-slice-upload, #btn-auto-upload').prop('disabled', false);
                    }
                });
            }
            
            // 添加到文件列表
            function addToFileList(file, data) {
                const fileInfo = {
                    name: file.name,
                    size: formatFileSize(file.size),
                    type: file.type,
                    url: data.url,
                    key: data.key,
                    fileId: data.file_id || null
                };
                
                uploadedFiles.push(fileInfo);
                updateFileList();
            }
            
            // 更新文件列表显示
            function updateFileList() {
                $('#uploaded-files').removeClass('hidden');
                const fileList = $('#file-list');
                fileList.empty();
                
                uploadedFiles.forEach((file, index) => {
                    const fileItem = $('<div class="file-item"></div>');
                    const fileInfo = $('<div class="file-info"></div>');
                    const fileName = $('<div class="file-name"></div>').text(file.name);
                    const fileSize = $('<div class="file-size"></div>').text(`大小: ${file.size} | 类型: ${file.type}`);
                    
                    fileInfo.append(fileName, fileSize);
                    
                    const fileActions = $('<div class="file-actions"></div>');
                    const viewBtn = $('<button class="btn-primary">查看</button>').click(() => {
                        window.open(file.url, '_blank');
                    });
                    
                    const copyBtn = $('<button class="btn-success">复制链接</button>').click(() => {
                        copyToClipboard(file.url);
                    });
                    
                    const deleteBtn = $('<button class="btn-danger">删除</button>').click(() => {
                        if (confirm(`确定要删除文件「${file.name}」吗？`)) {
                            deleteFile(file.key, index);
                        }
                    });
                    
                    fileActions.append(viewBtn, copyBtn, deleteBtn);
                    fileItem.append(fileInfo, fileActions);
                    fileList.append(fileItem);
                });
            }
            
            // 显示图片预览
            function showImagePreview(url) {
                $('.image-preview').remove();
                const img = $('<img class="image-preview" />').attr('src', url);
                $('#result').append(img);
            }
            
            // 删除文件
            function deleteFile(key, index) {
                $.ajax({
                    url: '/admin/cos_upload/delete',
                    type: 'POST',
                    data: { key: key },
                    success: function(res) {
                        if (res.code === 1) {
                            uploadedFiles.splice(index, 1);
                            updateFileList();
                            alert('文件删除成功');
                            
                            if (uploadedFiles.length === 0) {
                                $('#uploaded-files').addClass('hidden');
                            }
                        } else {
                            alert('文件删除失败：' + res.msg);
                        }
                    },
                    error: function() {
                        alert('删除请求失败');
                    }
                });
            }
            
            // 复制到剪贴板
            function copyToClipboard(text) {
                if (navigator.clipboard) {
                    navigator.clipboard.writeText(text).then(() => {
                        alert('链接已复制到剪贴板');
                    }).catch(() => {
                        fallbackCopyTextToClipboard(text);
                    });
                } else {
                    fallbackCopyTextToClipboard(text);
                }
            }
            
            function fallbackCopyTextToClipboard(text) {
                const textArea = document.createElement('textarea');
                textArea.value = text;
                document.body.appendChild(textArea);
                textArea.focus();
                textArea.select();
                
                try {
                    document.execCommand('copy');
                    alert('链接已复制到剪贴板');
                } catch (err) {
                    alert('复制失败，请手动复制：' + text);
                }
                
                document.body.removeChild(textArea);
            }
            
            // 格式化文件大小
            function formatFileSize(bytes) {
                if (bytes === 0) return '0 Bytes';
                
                const k = 1024;
                const sizes = ['Bytes', 'KB', 'MB', 'GB'];
                const i = Math.floor(Math.log(bytes) / Math.log(k));
                
                return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
            }
        });
    </script>
</body>
</html>